<template>
  <el-dialog :model-value="visible" title="改价" width="600px" align-center destroy-on-close @close="onClose">
    <el-form ref="formRef" :model="formModel" :rules="rules" label-width="80px" @submit.prevent>
      <el-form-item class="form-group" label="实付价格" prop="paidAmount">
        <el-input-number v-model="formModel.paidAmount" :min="0" controls-position="right" />
        <span class="tip">修改后，用户继续支付时的价格 </span>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="onClose()">取消</el-button>
      <el-button type="primary" @click="onSubmit()">确定</el-button>
    </template>
  </el-dialog>
</template>
<script setup>
  import { ElMessage } from 'element-plus'
  import { reactive, ref } from 'vue'
  import { commonApi } from '@/api/common'

  // 规则
  const formRef = ref()
  const rules = {
    paidAmount: [
      { required: true, message: '不能为空', trigger: 'blur' },
      { type: 'number', message: '请输入数字', trigger: 'blur' }
    ]
  }

  // 表单
  const emit = defineEmits(['refresh'])
  const loading = ref(false)
  const formDefault = {
    id: undefined,
    paidAmount: 0
  }
  const formModel = reactive({ ...formDefault })
  // 提交
  const onSubmit = async () => {
    // 校验
    const valid = await formRef.value.validate()
    if (!valid) return

    if (loading.value === true) {
      ElMessage.warning('正在处理···')
      return
    }
    loading.value = true
    try {
      if (formModel.id) {
        await commonApi.orderChangePrice(formModel)
        ElMessage.success('修改成功')
      }
      emit('refresh')
      onClose()
    } finally {
      loading.value = false
    }
  }

  // 打开和关闭
  const visible = ref(false)
  const onOpen = (item) => {
    if (item) {
      formModel.id = item.id
      formModel.paidAmount = item.paidAmount
    }
    visible.value = true
  }
  const onClose = () => {
    visible.value = false
    Object.assign(formModel, formDefault)
  }
  defineExpose({ onOpen })
</script>
